-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local class = require 'mc.class'
local lu = require 'luaunit'
local execute_chain = require 'infrastructure.chain'
local power_lock = require 'infrastructure.power_lock'

TestInsfrastructure = {}

local function _throws_error(err)
    if err then
        error(err)
    end
end

local Executor_1 = class()
function Executor_1:execute(ctx, chain)
    lu.assertEquals(ctx.packageType, '1')
    lu.assertEquals(ctx.Period, '2')
    ctx.packageType = '5'
    ctx.Period = '3'
    local err = chain:execute(ctx)
    ctx.packageType = '6'
    ctx.Period = '6'
    _throws_error(err)
end

local Executor_2 = class()
function Executor_2:execute(ctx, chain)
    lu.assertEquals(ctx.packageType, '5')
    lu.assertEquals(ctx.Period, '3')
    error('chain execute fail')
    _throws_error(chain:execute(ctx))
end

-- 1、测试执行链
function TestInsfrastructure:test_chain()
    local ctx = {
        packageType = '1',
        Period = '2'
    }
    local upgrade_chain = execute_chain.new()
    upgrade_chain:add(Executor_1.new())
    upgrade_chain:add(Executor_2.new())
    local err = upgrade_chain:execute(ctx)
    lu.assertNotEquals(err, nil)
    lu.assertEquals(ctx.packageType, '6')
    lu.assertEquals(ctx.Period, '6')
end

-- 2、测试lock
function TestInsfrastructure:test_lock()
    local lock = power_lock.new({})
    local res = lock:lock()
    lu.assertEquals(res, false)

    res = lock:finish_judge()
    lu.assertEquals(res, nil)

    lock:prolong_lock_task()
    lock:lock_forever()
    lock:unlock()
end